package com.seo.controller.index;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.seo.pojo.ReturnBody;
import com.seo.service.sysUser.sdk.SysUserService;
import com.seo.utils.Const;
import com.seo.utils.code.CaptchaUtils;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

/**
 * 首页controller <br/>
 * 
 * @author shibeilei
 * @version 2017.11.30 12:20
 */
@Slf4j
@Controller
@RequestMapping(value = "/login")
public class LoginController {

	@Autowired
	private SysUserService sysUserService;

	@RequestMapping
	public String login(HttpServletRequest request, HttpSession session) {
		log.info("进入登录页...");
		return "login";

	}

	@ApiOperation(value = "登录接口")
	@RequestMapping(value = "/toLogin", method = RequestMethod.POST)
	@ResponseBody
	public ReturnBody toLogin(
			@ApiParam(name = "loginName") @RequestParam String loginName,
			@ApiParam(name = "password") @RequestParam String password,
			@ApiParam(name = "code") @RequestParam String code, @ApiParam(hidden = true)HttpSession session) {
		log.info("登录...");
		ReturnBody rb = ReturnBody.init();
		if (StringUtils.isEmpty(loginName)) {
			return rb.error("error", "登录名不能为空");
		}
		if (StringUtils.isEmpty(password)) {
			return rb.error("error", "密码不能为空");
		}

		if (StringUtils.isEmpty(code)) {
			return rb.error("error", "验证码不能为空");
		}

		String sessionCode = (String) session.getAttribute(CaptchaUtils.CODE_SESSION);
		if (StringUtils.isEmpty(sessionCode)) {
			return rb.error("error", "验证码错误");
		}
		log.info("参数 loginName-{},password-{},code-{},sessionCode-{}", loginName, password, code, sessionCode);
		if (!sessionCode.equals(code.toUpperCase())) {
			return rb.error("error", "验证码错误");
		}

		rb = sysUserService.login(loginName, password, code);
		if (!rb.isSuccess()) {
			return rb;
		}
		Map<String, Object> sysUser = rb.get("sysUser", String.class, Object.class);
		session.setAttribute(Const.SESSION_USER, sysUser);
		return rb;

	}

	@RequestMapping("/outLogin")
	public String outLogin(HttpSession session) {
		session.removeAttribute(Const.SESSION_USER);
		session.removeAttribute(Const.SESSION_MENULIST);
		return "login";
	}

}
